<?php

namespace app\admin\controller;

use app\admin\controller\Common;
use think\Db;

class Content extends Common
{

    protected $table = 'content';
    protected $type = [
        '系统广播',
        '动态',
        '节目'
    ];

//    public function index()
//    {
//        $category = Db::name($this->table.'_category')->column('id, name');
//        $this->assign('category', $category);
//        // 筛选条件
//        $where = [];
//
//        if (input('?get.type')) {
//            switch (input('get.type/s')) {
//                case 'dynamic':
//                    $where['type'] = 1;
//                    break;
//                case 'show':
//                    $where['type'] = 2;
//                    break;
//                case 'system':
//                    $where['type'] = 0;
//                    break;
//                case 'content_id':
//                    $where['id'] = input('get.text/s', '');
//                    break;
//                default:
//                    $text = input('get.text/s', '');
//                    if ($text) {
//                        $where[] = ['content', 'like', "%{$text}%"];
//                    }
//            }
//        }
//
//
//
//        $type = $this->type;
//        $order_by = input('get.order/s', 'asc');
//        $data = Db::name($this->table)->where($where)->order('id ' . $order_by)->paginate()->each(function ($item, $key) use($type, $category) {
//            $item['apply_num'] = '';
//            $item['nickname'] = '系统 & 管理员';
//            if ($item['type'] == 2) {
//                $item['apply_num'] = Db::name($this->table . '_comment')->where(['content_id' => $item['id'], 'type' => 2])->count();
//            }
//            if ($item['member_id'] > 0) {
//                $nickname = Db::name('member')->where('id', $item['member_id'])->value('nickname');
//                $item['nickname'] = empty($nickname) ? '--' : $nickname;
//            }
//            $item['location'] = empty($item['location']) ? '--' : $item['location'];
//            $item['category_name'] = isset($category[$item['category_id']]) ? $category[$item['category_id']] : ' - ';
//            $item['date'] = ($item['begin_date'] == $item['end_date']) ? $item['begin_date'] . '一整天' : $item['begin_date'] . ' - ' .$item['end_date'];
//            $item['type'] = isset($type[$item['type']]) ? $type[$item['type']] : '';
//            return $item;
//        });
//        $this->assign('data', $data);
//        return $this->fetch();
//    }


    /**
     * User:Simony
     * Function: 内容页
     * @return mixed
     */
    public function index()
    {

        //params
        $id = input('get.id/d', 0);
        $text = input('get.text/s', '');
        $order_by = input('get.order/s', 'desc');
        $field = input('get.field', '');
        $value = input('get.value', '');

        //where
        $where = [];

        //judge
        if ($id) $where['id'] = $id;
        if ($text) $where[] = ['content', 'like', "%{$text}%"];
        if ($field && $value) $where[$field] = $value;

        //model
        $contentModel = model('common/content/Content');
        $categoryModel = model('common/content/Category');

        //getData
        $category = $categoryModel->getCol('id, name');
        $data = $contentModel->getContentList($where, $category, 'id ' . $order_by);

        //assign
        $this->assign('data', $data);
        $this->assign('category', $category);
        $this->assign('types', $contentModel->types);
        $choose_list = config('app.choose_list');
        $this->assign("choose_list", $choose_list);
        return $this->fetch();
    }

    public function add()
    {
        $fileModel = model('common/member/File');
        $contentModel = model('common/content/Content');
        $choose_list = config('app.choose_list');
        if ($this->request->isAjax()) {
            $data = $this->request->post();

            $validate = validate('content');
            if (!$validate->check($data)) {
                return ['err' => $validate->getError()];
            }
            $id = intval($data['id']);
            unset($data['id']);
            $img_ids = explode(',', $data['image_ids']);
            unset($data['image_ids']);
            $file = $data['file'] ?? [];
            unset($data['file']);
            $delete = empty($img_ids) ? array() : array_diff($img_ids, array_keys($file));
            $delete = empty($delete[0]) ? [] : $delete;

            if ($data['choose'] == 1) { //选择
                if (empty($data['date'])) return ['err' => '时间不能为空'];
                $begin_date = $data['date'] . ' ' . $choose_list[$data['date_type']]['begin_date'];
                $end_date = $data['date'] . ' ' . $choose_list[$data['date_type']]['end_date'];

            } else {//自行填写
                $begin_date = $data['begin_date'];
                $end_date = $data['end_date'];
                $data['date_type'] = -1;
            }

            unset($data['date']);
            unset($data['choose']);
            if (empty($begin_date) || empty($end_date)) return ['err' => '时间不能为空'];
            $data = array_merge($data, array(
                'begin_date' => strtotime($begin_date),
                'end_date' => strtotime($end_date),
                'update_time' => time()
            ));

            if ($id > 0) {
                $isSave = $contentModel->editByID($id, $data);
            } else {
                $data['create_time'] = $data['update_time'];
                $isSave = $contentModel->add($data);
                if ($isSave) {
                    $id = $isSave;
                }
            }
            if ($isSave) {
                // 处理文件
                if ($delete) {
                    foreach ($delete as $file_id) {
                        $file = $fileModel->getInfoByID($file_id);
                        if ($file) {
                            $fileModel->delByID($file_id);
                            $fileLogic = model('common/file/FileLogic','logic');
                            if($fileLogic->fileExists ($file['url'])) $fileLogic->deleteFile($file['url']);
                        }
                    }
                }
                foreach ($file as $file_id => $file_data) {
                    $fileModel->editByID($file_id, [
                        'table_id' => $id,
                        'member_id' => isset($data['member_id']) ? intval($data['member_id']) : 0,
                        'remark' => $file_data['remark'],
                        'status' => $file_data['status']
                    ]);
                }
                return ['ret' => '保存成功'];
            }
            return ['err' => '保存失败，请重试'];
        }
        $file = array();
        if (input('?get.id')) {
            $name = $contentModel->getInfoByID(input('get.id/d'));
            $this->assign('name', $name);
            if ($name) {
                $file = $fileModel->getCol('id, status, url, remark', ['table_id' => $name['id'], 'type' => 5, 'member_id' => $name['member_id']]);
            }
        }
        $categoryModel = model('common/content/Category');
        $config = [
            'type' => $contentModel->types,
            'category' => $categoryModel->getList([], 0, 'id, name', 'order asc')
        ];
        $this->assign('file', $file);
        $this->assign('config', $config);
        $this->assign("choose_list", $choose_list);
        return $this->fetch();
    }

    public function audit()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d');
            $type = input('post.type/d');
            if (empty($id) || empty($type)) {
                return json(['status' => 0, 'msg' => '缺少必要参数']);
            }
            if (!in_array($type, [1, 2, 3])) {
                return json(['status' => 0, 'msg' => '审核状态错误']);
            }
            $contentModel = model('common/content/Content');
            $content = $contentModel->getInfoByID($id);
            if (empty($content)) {
                return json(['status' => 0, 'msg' => '内容不存在']);
            }
            if ($type == $content['audit_type']) {
                return json(['status' => 0, 'msg' => '审核状态未改变']);
            }
            $update = [
                'audit_type' => $type,
                'audit_time' => 0
            ];
            if ($type == 2) {
                $update['audit_time'] = time();
            }
            if ($contentModel->editByID($content['id'], $update)) {
                switch ($type) {
                    case 1:
                        $msg = '待审';
                        break;
                    case 2:
                        $msg = '审核';
                        break;
                    default:
                        $msg = '拒绝';
                }
                $msg .= '成功';
                return json(['status' => 1, 'msg' => $msg]);
            }
            return json(['status' => 0, 'msg' => '审核失败，请再试一次']);
        }
        return json(['status' => 0, 'msg' => '请求方式有误']);
    }

    public function del()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d');
            if (!$id) {
                return ['err' => '缺少必要参数'];
            }
            $content = Db::name($this->table)->where('id', $id)->find();
            if (empty($content['id'])) {
                return ['err' => '内容不存在或已删除'];
            }
            $this->delFile($content['id']);
            $comment = Db::name($this->table . '_comment')->where('content_id', $content['id'])->delete();
            if (!$comment) {
                return ['err' => '删除失败1，请重试！'];
            }
            $content = Db::name($this->table)->delete($content['id']);
            if (!$content) {
                return ['err' => '删除失败2，请重试！'];
            }
            return ['ret' => '删除成功'];
        }
        return ['err' => '请求方式有误'];
    }

    public function batchOperate()
    {
        if ($this->request->isAjax()) {
            $ids = input('post.ids/s', '');
            $type = input('post.type/s', '');
            if (empty($ids) || empty($type)) {
                return json(['status' => 0, 'msg' => '缺少必要参数']);
            }
            $content = Db::name($this->table)->where('id', 'in', $ids)->column('id');
            if (!$content) {
                return json(['status' => 0, 'msg' => '内容不存在或已删除']);
            }
            foreach ($content as $id) {
                if ($type == 'del') {
                    $this->delFile($id);
                    Db::name($this->table . '_comment')->where('content_id', $id)->delete();
                    Db::name($this->table)->delete($id);
                } else {
                    $update = [
                        'audit_type' => $type,
                        'audit_time' => 0
                    ];
                    if ($type == 2) {
                        $update['audit_time'] = time();
                    }
                    Db::name($this->table)->where('id', $id)->update($update);
                }
            }
            return json(['status' => 1, 'msg' => '操作成功']);
        }
        return json(['status' => 0, 'msg' => '请求方式有误']);
    }

    protected function delFile($contentId)
    {
        $table = 'member_file';
        $files = Db::name($table)->where(['table_id' => $contentId, 'type' => 5])->field('id, url')->select();
        $comment = Db::name($this->table . '_comment')->where('content_id', $contentId)->column('id, member_id');
        if ($comment) {
            $comment_files = Db::name($table)->where(['table_id' => array_keys($comment), 'type' => 6])->field('id, url')->select();
            if ($comment_files) $files = array_merge($files, $comment_files);
        }
        if ($files) {
            foreach ($files as $file) {
                Db::name($table)->delete($file['id']);
                $fileLogic = model('common/file/FileLogic','logic');
                if($fileLogic->fileExists ($file['url'])) $fileLogic->deleteFile($file['url']);
            }
        }
        return $comment;
    }

    public function category()
    {
        $text = input('get.text', '');
        $where = [];
        if ($text) {
            $where[] = ['name', 'like', "%{$text}%"];
        }
        $data = Db::name($this->table . '_category')->where($where)->order('order asc')->paginate();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function categoryAdd()
    {
        $table = $this->table . '_category';
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            if (!isset($data['id']) || !isset($data['hide']) || empty($data['name']) || !isset($data['order']) || empty($data['icon_type'])) {
                return ['err' => '缺少必要参数'];
            }
            if ($data['icon_type'] == 1) {
                if (empty($data['icon_choose'])) {
                    return ['err' => '请选择默认图标'];
                }
                $data['icon'] = $data['icon_choose'];
            }
            if ($data['icon_type'] == 2) {
                if (empty($data['icon_upload'])) {
                    return ['err' => '请上传图标'];
                }
                $data['icon'] = $data['icon_upload'];
            }
            unset($data['icon_upload']);
            unset($data['icon_type']);
            unset($data['icon_choose']);
            $data['name'] = trim($data['name']);
            $category = Db::name($table)->where('name', $data['name'])->find();
            if ($category && intval($data['id']) !== $category['id']) {
                return ['err' => '名称不允许重复'];
            }
            $data['update_time'] = time();
            if ($data['id'] > 0) {
                $isSave = Db::name($table)->where('id', $data['id'])->update($data);
            } else {
                $data['create_time'] = $data['update_time'];
                $isSave = Db::name($table)->insert($data);
            }
            if ($isSave) {
                return ['ret' => '保存成功'];
            }
            return ['err' => '保存失败，请重试'];
        }
        if (input('?get.id')) {
            $name = Db::name($table)->where('id', input('get.id/d', 0))->find();
            $this->assign('name', $name);
        }
        $icons = array();
        for ($i = 1; $i < 9; $i++) {
            $icons[] = "/style/index/images/list_nav_0{$i}.png";
        }
        $this->assign('icons', $icons);
        return $this->fetch();
    }

    public function categoryDel()
    {
        if ($this->request->isAjax()) {
            $table = $this->table . '_category';
            $id = input('post.id/d', '');
            if (!$id) {
                return ['err' => '缺少必要参数'];
            }
            $category = Db::name($table)->where('id', $id)->find();
            if (!$category) {
                return ['err' => '分类不存在或已删除'];
            }
            if (Db::name($table)->delete($id)) {
                return ['ret' => '删除成功'];
            }
            return ['err' => '删除失败，请重试'];
        }
        return ['err' => '请求方式有误'];
    }


    public function comment()
    {

        //params
        $content_id = input('get.content_id/d', '');
        $field = input('get.field', '');
        $value = input('get.value', '');
        $search_field = input('get.search_field', '');
        $search_value = input('get.search_value', '');

        //where
        $where = [];
        $content_id && $where['content_id'] = $content_id;
        $field && $value && $where[$field] = $value;
        $search_field && $search_value && $where[$search_field] = $search_value;

        //model
        $commentModel = model('common/content/Comment');

        //getData
        $data = $commentModel->getContentCommentList($where, 10);

        //assign
        $this->assign('data', $data);
        $this->assign('page', $commentModel->page_info->render());
        return $this->fetch();
    }


    public function commentDel()
    {
        if ($this->request->isAjax()) {

            //params
            $id = input('post.id/d', '');

            //model
            $commentModel = model('common/content/Comment');

            //judge
            if (!$id) ds_json_encode('err', '缺少必要参数');

            //data
            $res = $commentModel->delByID($id);

            $res ? ds_json_encode('ret', '删除成功') : ds_encode('err', '删除失败');
        }
        ds_json_encode('err', '请求方式有误');
    }


    public function commentAdd()
    {
        //params
        $id = input("id/d");

        //model
        $contentModel = model('common/content/Content');
        $commentModel = model('common/content/Comment');

        //getData
        $comment = $commentModel->getInfoByID($id);
        $content = $contentModel->getInfoByID($comment['content_id']);

        //where
        $cond = [
            'content_id' => $content['id'],
            'pid' => $comment['pid'],
        ];

        $comment_list = $commentModel->getContentCommentList($cond, 1);
        $this->assign('page', $commentModel->page_info->render());
        $this->assign('comment_list', $comment_list);
        $this->assign('comment', $comment);
        $this->assign('content', $content);

        $this->assign('prev', $comment['pid'] == 0 ? 0 : 1);

        return $this->fetch();
    }

    public function proclamation()
    {
        $model = model('common/content/Proclamation');
        $where = [];
        $type = input('get.type/s', '');
        $text = input('get.text/s', '');
        if ($type && $text) {
            if (($type !== 'id')) $text = '%' . $text . '%';
            $where[] = [$type, (($type == 'id') ? '=' : 'like'), $text];
        }
        $data = $model->getList($where);
        $page = $model->page_info->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function proclamationAdd()
    {
        $model = model('common/content/Proclamation');
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $validate = validate('Proclamation');
            if (!$validate->check($data)) {
                return ['err' => $validate->getError()];
            }
            $id = $data['id'];
            unset($data['id']);
            $data['update_time'] = time();
            if ($id > 0) {
                $isSave = $model->edit(['id' => $id], $data);
            } else {
                $data['create_time'] = $data['update_time'];
                $isSave = $model->add($data);
            }
            if ($isSave) {
                return ['ret' => '保存成功'];
            }
            return ['err' => '保存失败，请再试一次'];
        }
        $id = input('get.id/d');
        $name = [];
        if ($id) {
            $name = $model->getInfo(['id' => $id]);
        }
        $this->assign('name', $name);
        return $this->fetch();
    }

    public function proclamationDel()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d', '');
            if (!$id) {
                return ['err' => '缺少必要参数'];
            }
            $model = model('common/content/Proclamation');
            $proclamation = $model->getInfo(['id' => $id]);
            if (empty($proclamation)) {
                return ['err' => '公告不存在或已删除'];
            }
            if ($model->delByID($proclamation['id'])) {
                return ['ret' => '删除成功'];
            }
            return ['err' => '删除失败，请再试一次'];
        }
        return ['err' => '请求方式有误'];
    }


    /**
     * User:Simony
     * Function: 内容类型列表
     * @return mixed
     */
    public function typeList()
    {
        //params
        $field = input('get.field', '');
        $value = input('get.value', '');
        $search_field = input('get.search_field', '');
        $search_value = input('get.search_value', '');

        //where
        $where = [];

        //judge
        if ($field) $where[$field] = $value;
        if ($search_field) $where[$search_field] = $search_value;

        //model
        $contentTypeModel = model('common/content/ContentType');

        //getData
        $list = $contentTypeModel->getList($where, 0, '*', 'order desc');


        $list = get_tree_option($list, 0, 'pid');

        //assign
        $this->assign('list', $list);

        return $this->fetch();
    }


    /**
     * User:Simony
     * Function: 内容类型添加修改
     */
    public function typeAdd()
    {
        //params
        $id = input('param.id/d', '');

        //model
        $contentTypeModel = model('common/content/ContentType');
        $data = $contentTypeModel->getInfoByID($id);

        if ($this->request->isAjax()) {

            //post params
            $ajax_data = $this->request->post();
            /*$validate = validate('ContentType');
            if (!$validate->check($ajax_data)) {
               return ['err' => $validate->getError()];
           }*/
            //judge
            if ($id && !$data) ds_json_encode('err', '数据不存在');

            $res = $id ? $contentTypeModel->edit(['id' => $id], $ajax_data) : $contentTypeModel->add($ajax_data);
            $res ? ds_json_encode('ret', '操作成功') : ds_json_encode('err', '操作失败');
        }


        $list = $contentTypeModel->getList([]);
        $list = get_tree_option($list, 0, 'pid');


        $this->assign('data', $data);
        $this->assign('list', $list);
        return $this->fetch();
    }
}
